package Donnees;

import Presentation.FenetrePrincipale;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

public class ConnectionFactory {

	//static reference to itself
	private static final ConnectionFactory instance = new ConnectionFactory();
	public static String URL;
	public static String USER;
	public static String PASSWORD;
	public static String DRIVER_CLASS;

	//private constructor
	private ConnectionFactory() {
		try {
			try {
				Properties props = new Properties();
				FileInputStream  fis = new FileInputStream("db.properties");
				props.load(fis);
				this.DRIVER_CLASS = props.getProperty("DRIVER_CLASS");
				this.URL = props.getProperty("URL");
				this.USER = props.getProperty("USERNAME");
				this.PASSWORD = props.getProperty("PASSWORD");
			} catch (Exception e) {
				System.out.println("Fichier db.properties introuvable, utilisation des valeurs par defaut.");
				this.URL = "jdbc:mysql://37.187.106.213:3306/cdegp";
				this.USER = "cdegp";
				this.PASSWORD = "passcdegp";
				this.DRIVER_CLASS = "com.mysql.jdbc.Driver";
			}
			Class.forName(DRIVER_CLASS);
		} catch (ClassNotFoundException e) {
                    ResourceBundle configBundle = ResourceBundle.getBundle("ressources/Main/Main", Locale.FRENCH);
                    FenetrePrincipale.afficherPopupErreur(configBundle.getString("main.errConnexion"));
                    e.printStackTrace();
		}
	}

	private Connection createConnection() throws SQLException {
            Connection connection;
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
            return connection;
	}

	public static Connection getConnection() throws SQLException {
            return instance.createConnection();
	}
}
